import React, { useEffect, useState } from 'react'
import { createPortal } from 'react-dom'
import { Image, Ellipsis, NavBar, Skeleton, Footer, Modal, Dialog, SpinLoading } from 'antd-mobile'
import styles from './index.module.less'
import { DeleteOutline, EditSOutline, EyeOutline, CheckCircleOutline } from 'antd-mobile-icons'
import CheckIcon from '../../assets/icons/check.svg'
import logoIcon from '../../../logo-icon.svg'
import { showErrorToast } from '../../utils/customToast'
const { getWorldBookDetails, importWorldBook } = $globalServicer('world')

const DetailModal = ({ visible, onClose, worldId }) => {
    const [worldInfo, setWorldInfo] = useState(null)
    const [loading, setLoading] = useState(false)
    const [importLoading, setImportLoading] = useState(false)
    const [imported, setImported] = useState(false)
    const [imageExpanded, setImageExpanded] = useState(false) // 添加图片放大状态
    const customNavigate = $globalNavigate()

    const handleAddToMyCollection = () => {
        // 没有导入过，执行导入逻辑
        setImportLoading(true)
        importWorldBook({
            id: worldId
        }).then(res => {
            setImportLoading(false)
            setImported(true) // 设置导入成功状态
            Dialog.alert({
                title: '导入成功',
                content: (
                    <div style={{
                        textAlign: 'center',
                        padding: '24px 16px',
                        color: '#000'
                    }}>
                        <CheckCircleOutline style={{
                            fontSize: '64px',
                            color: '#52c41a',
                            marginBottom: '20px'
                        }} />
                        <p style={{
                            fontSize: '16px',
                            color: '#fff',
                            margin: '0 0 8px 0',
                            fontWeight: '500'
                        }}>
                            智能体已成功导入到智能体库中
                        </p>
                        <p style={{
                            fontSize: '14px',
                            color: '#fff',
                            margin: 0
                        }}>
                            现在您可以开始与它对话了
                        </p>
                    </div>
                ),
                confirmText: '知道了',
                onConfirm: () => {
                    console.log('用户确认了导入成功提示')
                }
            })
        }).catch(error => {
            setImportLoading(false)
            showErrorToast('导入失败，请重试');
        })
    }

    useEffect(() => {
        if (visible && worldId) {
            setLoading(true)
            setImported(false) // 重置导入状态
            getWorldBookDetails(worldId).then(res => {
                console.log(`------res`, res)
                setWorldInfo(res)
            }).finally(() => {
                setLoading(false)
            });
        } else if (!visible) {
            // 弹窗关闭时重置状态
            setImported(false)
            setWorldInfo(null)
        }
    }, [visible, worldId])

    if (!visible) return null

    const modalContent = (
        <Modal
            visible={visible}
            onClose={onClose}
            closeOnMaskClick={true}
            bodyStyle={{
                padding: 0,
                height: '80vh',
                overflow: 'auto',
                width: '90vw',
                maxWidth: '500px'
            }}
            content={
                <div className={`${styles.container} dark-theme`}>
                    <div className={styles.header}>
                        <div className={styles.headerContent}>
                            <h2 className={styles.title}>{worldInfo?.name || '加载中...'}</h2>
                            <button className={styles.closeButton} onClick={onClose}>
                                <i className="material-icons">close</i>
                            </button>
                        </div>
                    </div>


                    {loading ? (
                        <div className={styles.loadingContainer}>
                            <Skeleton.Title animated />
                            <Skeleton.Paragraph lineCount={5} animated />
                        </div>
                    ) : worldInfo ? (
                        <>
                            <div className={styles.heroSection}
                                 onClick={() => setImageExpanded(true)} // 添加点击事件
                            >
                                {/* 使用img标签替代background-image */}
                                <img 
                                    src={worldInfo?.cover} 
                                    alt={worldInfo?.name}
                                    className={styles.heroImage}
                                />
                                <div className={styles.heroOverlay}>
                                    <div className={styles.viewCount}>
                                        <img src={CheckIcon} alt="check" style={{ width: '16px', height: '16px' }} />
                                        <span>{worldInfo?.view}</span>
                                    </div>
                                </div>
                                {/* 添加点击提示 */}
                                <div className={styles.imageClickHint}>
                                    <i className="material-icons">zoom_in</i>
                                    <span>点击查看大图</span>
                                </div>
                            </div>

                            <div className={styles.contentWrapper}>
                                <div className={styles.titleSection}>
                                <h1 className={styles.title}>{worldInfo?.name}</h1>
                                    <p className={styles.description}>
                                        {worldInfo?.description}
                                    </p>
                                </div>

                                {
                                    worldInfo?.is_show && !imported && (
                                        <div className={styles.actionSection}>
                                            <button
                                                className={styles.actionButton}
                                                onClick={handleAddToMyCollection}
                                                disabled={importLoading}
                                            >
                                                {importLoading ? (
                                                    <>
                                                        <SpinLoading style={{'--size': '18px', color: '#ffffff'}}/>
                                                        <span className={styles.buttonText}>导入中...</span>
                                                    </>
                                                ) : (
                                                    <>
                                                <span className={styles.buttonIcon}>
                                                    {worldInfo?.is_show ? <img src={logoIcon} alt="logo" style={{width: '25px', height: '25px'}} /> : '📝'}
                                                </span>
                                                        <span className={styles.buttonText}>
                                                    {worldInfo?.is_show ? '导入智能体库' : '复制编辑'}
                                                </span>
                                                        <span className={styles.buttonArrow}>→</span>
                                                    </>
                                                )}
                                            </button>
                                        </div>
                                    )
                                }

                            </div>
                        </>
                    ) : (
                        <div className={styles.errorContainer}>
                            <p>加载失败，请重试</p>
                        </div>
                    )}
                </div>
            }
        />
    )

    // 图片放大弹窗
    const imageModal = imageExpanded && (
        <Modal
            visible={imageExpanded}
            onClose={() => setImageExpanded(false)}
            closeOnMaskClick={true}
            bodyStyle={{
                padding: 0,
                height: '90vh',
                width: '95vw',
                maxWidth: '800px',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center'
            }}
            content={
                <div className={styles.imageModalContainer}>
                    <img 
                        src={worldInfo?.cover} 
                        alt={worldInfo?.name}
                        className={styles.fullSizeImage}
                        onClick={() => setImageExpanded(false)}
                    />
                    <button 
                        className={styles.closeImageButton}
                        onClick={() => setImageExpanded(false)}
                    >
                        <i className="material-icons">close</i>
                    </button>
                </div>
            }
        />
    )

    // 使用 createPortal 将 Modal 渲染到 document.body
    return createPortal(
        <>
            {modalContent}
            {imageModal}
        </>, 
        document.body
    )
}

export default DetailModal
